package com.pmcc.core.web;

import com.pmcc.core.entity.security.Region;
import com.pmcc.core.repository.RegionRepository;
import com.pmcc.core.service.RegionService;
import com.pmcc.utils.ResultBean;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chuLiDong on 2018/5/27.
 */
@RestController()
@RequestMapping("api/v1/region")
@Api(value = "RegionController", description = "地区api")
public class RegionController {

    @Autowired
    RegionService regionService;

    @Autowired
    RegionRepository regionRepository;

    /**
     * 查询地区分类树
     *
     * @return
     */
    @RequestMapping(value = "/queryRegionTree", method = RequestMethod.GET)
    @ResponseBody
    public ResultBean queryRegionTree(Region region) {
        ResultBean resultBean = new ResultBean();
        resultBean.setResultCode(ResultBean.SUCCESS);
        resultBean.setResultDesc("查询成功！");
        resultBean.setRows(regionService.queryRegionTree(region));
        return resultBean;
    }

    /**
     * 根据父节点查询孩子
     *
     * @param parentId
     * @param flag     1 需要对直辖市做出处理
     * @return
     */
    @RequestMapping(value = "/queryByParentId", method = RequestMethod.GET)
    @ResponseBody
    public ResultBean queryByParentId(String parentId, String flag) {
        ResultBean resultBean = new ResultBean();
        resultBean.setResultCode(ResultBean.SUCCESS);
        resultBean.setResultDesc("查询成功！");
        Region region = regionRepository.findOne(parentId);
        if (region != null && StringUtils.isNotEmpty(region.getType()) && region.getType().equals("1") && flag.equals("2")) {
            List<Region> list = new ArrayList<>();
            list.add(region);
            resultBean.setRows(list);
        } else {
            resultBean.setRows(regionRepository.findByParentIdOrderByCode(parentId));
        }
        return resultBean;
    }


}
